import {stopPullDownRefresh, useLoad, usePullDownRefresh, useReachBottom} from "@tarojs/taro";
import {Text, View} from "@tarojs/components";
import React, {useEffect, useMemo, useState} from "react";
import {Button, Cascader, Cell, Popup, SafeArea} from "@taroify/core";
import OrderList from "@/components/orderList";
import {orderType} from "@/types";
import http from "@/request";
import {HideLoading, ShowLoading, ShowToast, ToPage} from "@/utils";
import user from "@/store/user";
import "./index.scss";
import TypeSelector from "@/pages/batch-dispatch/TypeSelector";
import chinaAreas from '@/store/chinaAreas';
import { Search } from "@taroify/core"

const pageConfig = {
    pageSize: 10,
    pageNum: 1,
    current: 1,
    total: 0
}
const BatchDispatch: React.FC = () => {
    const [open, setOpen] = useState(false);
    const [areas, setAreas] = useState<string[]>([]);
    const [displayValue, setDisplayValue] = useState<string>('');
    const [orders, setOrders] = useState<orderType[]>([]);
    const [selectedOrders, setSelectedOrders] = useState<string[]>([]);
    const [noMore, setNoMore] = useState(false)
    const [dispatchType, setDispatchType] = useState('2');
    const [areaFilter, setAreaFilter] = useState<{
        provinceCode?: string
        cityCode?: string
        areaCode?: string
    }>({});
    const userInfo = user.info;

    const typeChange = (val: string) => {
        setSelectedOrders([])
        setDispatchType(val)
        // 重新设置订单列表，清空选中状态
        setOrders(prev => prev.map(order => ({
            ...order,
            checked: false
        })));
        setNoMore(false)
    }

    useEffect(() => {
        if (!open) {
            pageConfig.pageNum = 1;
            setNoMore(false)
            queryOrderList();
        }
    }, [areaFilter, dispatchType, open])

    useLoad(() => {
        queryOrderList();
        chinaAreas.useChinaAreasStore()
    });

    usePullDownRefresh(() => {
        pageConfig.pageNum = 1
        setNoMore(false)
        queryOrderList();
    });

    useReachBottom(() => {
        if (!noMore) {
            pageConfig.pageNum++
            queryOrderList()
        }
    })

    const queryOrderList = () => {
        ShowLoading();
        const filter = userInfo?.teamLeaderFlag === 'T'
            ? {
                bizTeamId: userInfo?.teamId,
                status: dispatchType === '2' ? 'SeatAssignment' : 'TeamAssignment'
            }
            : {
                userCode: userInfo?.userCode,
                status: 'TeamAssignment'
            };
        const {pageNum, pageSize} = pageConfig

        http.post('/disp/biz/order/pageForWx', {
            ...filter,
            ...areaFilter,
            pageNum,
            pageSize
        }).then(res => {
            const newList = res.data.list || [];
            if (pageNum === 1) {
                setOrders(newList);
            } else {
                setOrders(prev => [...prev, ...newList]);
            }
            pageConfig.total = res.data.total;
            setNoMore(pageNum * pageSize >= pageConfig.total)
        }).finally(() => {
            HideLoading();
            stopPullDownRefresh();
        });
    };

    const openDispatchForm = () => {
        if (selectedOrders.length === 0) {
            ShowToast('请选择订单');
            return;
        }
        // 获取第一个选中订单的团队ID
        const firstOrder = orders.find(order => String(order.id) === selectedOrders[0]);
        if (!firstOrder?.bizTeamId) {
            return;
        }
        // 跳转到派单页面，带上选中的订单ID和团队ID
        ToPage(`/pages/order-change/index?ids=${selectedOrders.join(',')}&teamId=${firstOrder.bizTeamId}&type=dispatch`);
    }

    const handleSetAreas = (areas) => {
        setAreas(areas)
        setAreaFilter({
            provinceCode: areas[0],
            cityCode: areas[1],
            areaCode: areas[2]
        })
    }

    const [keyword, setKeyword] = useState("");

    // 定义地区数据类型
    interface RegionData {
        childRegion?: RegionData[];
        fullName: string;
        name: string;
        pregion: number;
        region: number;
        regionLevel: number;
        shortName: string;
        pinyin?: string;
    }

    function searchRegions(regions: RegionData[], keyword: string): RegionData[] {
        // 1. 处理空数据或无效输入
        if (!regions || !Array.isArray(regions)) {
            console.warn('行政区数据无效');
            return [];
        }

        // 2. 空关键字返回全量数据
        if (!keyword || !keyword.trim()) {
            return [...regions];
        }

        const keywordLower = keyword.toLowerCase().trim();
        
        // 3. 递归搜索函数，用于在树结构中查找匹配的节点
        const searchInTree = (nodes: RegionData[], parentPath: RegionData[] = []): RegionData[] => {
            const results: RegionData[] = [];
            
            for (const node of nodes) {
                const currentPath = [...parentPath, node];
                
                // 检查当前节点是否匹配
                const isMatch = node.fullName?.toLowerCase().includes(keywordLower) ||
                               node.name?.toLowerCase().includes(keywordLower) ||
                               node.shortName?.toLowerCase().includes(keywordLower);
                
                // 递归搜索子节点
                const childResults = node.childRegion ? searchInTree(node.childRegion, currentPath) : [];
                
                // 如果当前节点匹配或有子节点匹配，则包含当前节点
                if (isMatch || childResults.length > 0) {
                    // 创建节点的副本，避免修改原始数据
                    const resultNode = { ...node };
                    
                    // 如果有子节点匹配，保留匹配的子节点
                    if (childResults.length > 0) {
                        resultNode.childRegion = childResults;
                    }
                    
                    results.push(resultNode);
                }
            }
            
            return results;
        };

        // 4. 执行搜索
        const searchResults = searchInTree(regions);
        
        // 5. 如果搜索结果为空，尝试模糊匹配
        if (searchResults.length === 0) {
            return searchRegionsFuzzy(regions, keywordLower);
        }
        
        return searchResults;
    }

    // 模糊搜索函数，用于处理没有精确匹配的情况
    function searchRegionsFuzzy(regions: RegionData[], keyword: string): RegionData[] {
        const results: RegionData[] = [];
        const visited = new Set<number>();
        
        const searchFuzzy = (nodes: RegionData[], parentPath: RegionData[] = []) => {
            for (const node of nodes) {
                if (visited.has(node.region)) continue;
                visited.add(node.region);
                
                const currentPath = [...parentPath, node];
                
                // 更宽松的匹配条件
                const isMatch = 
                    node.fullName?.toLowerCase().includes(keyword) ||
                    node.name?.toLowerCase().includes(keyword) ||
                    node.shortName?.toLowerCase().includes(keyword) ||
                    // 拼音匹配（如果有拼音字段）
                    (node.pinyin && node.pinyin.toLowerCase().includes(keyword)) ||
                    // 首字母匹配
                    (node.name && node.name.toLowerCase().startsWith(keyword)) ||
                    (node.shortName && node.shortName.toLowerCase().startsWith(keyword));
                
                if (isMatch) {
                    // 构建完整的路径节点
                    const pathNodes = currentPath.map(pathNode => ({
                        ...pathNode,
                        childRegion: pathNode.childRegion ? [...pathNode.childRegion] : undefined
                    }));
                    
                    // 只添加根节点，但确保路径完整
                    if (pathNodes.length > 0) {
                        const rootNode = pathNodes[0];
                        if (!results.some(r => r.region === rootNode.region)) {
                            results.push(rootNode);
                        }
                    }
                }
                
                // 继续搜索子节点
                if (node.childRegion) {
                    searchFuzzy(node.childRegion, currentPath);
                }
            }
        };
        
        searchFuzzy(regions);
        return results;
    }

    const optionsTree = useMemo(() => {
        const regionsData = Array.isArray(chinaAreas.data) ? chinaAreas.data : [];
        console.log(searchRegions(regionsData, keyword))
        return searchRegions(regionsData, keyword)
    }, [chinaAreas.data, keyword])

    return (
        <View className="page flex-column">
            <Cell
                clickable
                title="选择地区"
                isLink={!displayValue}
                onClick={() => setOpen(true)}
                rightIcon={displayValue ? (
                    <View
                        className="iconfont icon-base-close2"
                        onClick={(e) => {
                            e.stopPropagation();
                            handleSetAreas([])
                            setDisplayValue('');
                            setAreaFilter({})
                        }}
                    />
                ) : undefined}
            >
                <Text className={displayValue ? 'has-value' : ''}>
                    {displayValue || '请选择'}
                </Text>
            </Cell>
            {
                userInfo?.teamLeaderFlag === 'T' ?
                    <TypeSelector
                        value={dispatchType}
                        onChange={typeChange}/> :
                    null
            }
            <OrderList
                orderList={orders}
                showCheckbox={true}
                selectedOrders={selectedOrders}
                onSelectChange={(selectedIds) => {
                    setSelectedOrders(selectedIds);
                }}
            />
            {
                <View className="load-more">{noMore ? '所有数据加载完毕' : '上划加载更多'}</View>
            }
            <View className="safe-area-bottom">
                <SafeArea position="bottom">
                    <Button shape="round" block color="primary" onClick={openDispatchForm}>
                        批量派单 ({selectedOrders.length})
                    </Button>
                </SafeArea>
            </View>
            <Popup
                open={open}
                placement="bottom"
                onClose={setOpen}>
                <Popup.Close />
                {
                    open ?
                        <View className="picker-body">
                            <View className="title">请选择地区</View>
                            <Search
                                shape="round"
                                value={keyword}
                                placeholder="请输入搜索关键词"
                                onChange={(e) => setKeyword(e.detail.value)}
                            />
                            <Cascader
                                options={optionsTree}
                                fieldNames={{
                                    label: 'name',
                                    value: 'region',
                                    children: 'childRegion'
                                }}
                                value={areas}
                                placeholder="请选择"
                                onSelect={(val, options) => {
                                    handleSetAreas(val)
                                    setDisplayValue(options.map(item => item.children).join('/'))
                                }}
                                onChange={(_values_, options) => {
                                    setOpen(false)
                                    setDisplayValue(options.map(item => item.children).join('/'))
                                }}
                            />
                        </View>:
                        null
                }
            </Popup>
        </View>
    )
}

export default BatchDispatch;